package interfaces.hud.topWindows;

import logic.common.game.Game;
import logic.common.player.Player;
import logic.common.team.Team;
import logic.common.team.teamListeners.DroneKillEvent;
import logic.common.team.teamListeners.TeamListener;
import logic.common.team.teamListeners.TeamValueChangedEvent;
import logic.common.team.teamListeners.TeamValueType;

import org.fenggui.binding.render.ImageFont;
import org.fenggui.util.Color;

import interfaces.GUISource;
import interfaces.hud.BasicHUD;
import interfaces.superWidgets.InterfaceLabel;

public class TDMStatusWindow extends TopHUDWindow {
	
	private InterfaceLabel scoreTeamA, scoreTeamB;
	private ImageFont labelFont;
	private int labelY, labelHeight, labelWidth;
	
	public TDMStatusWindow(BasicHUD hud, Game game) {
		super(game, hud, hud.getWidth() / 6, hud.getHeight() / 20);
		
		labelFont = GUISource.bigFont;
		labelY = 0;
		labelHeight = content.getHeight();
		labelWidth = content.getWidth() / 3;
		
		initScoreLabels();
		initListener(game.getTeamA());
		initListener(game.getTeamB());
		
		InterfaceLabel scoreLimitLabel = getNewScoreLabel(content.getWidth() / 5 * 2);
		GUISource.setTextColor(scoreLimitLabel, Color.BLACK);
		scoreLimitLabel.setText(game.getGameCycle().getScoreLimit() + "");
		
		layout();
	}
	
	private void initScoreLabels() {
		scoreTeamA = getNewScoreLabel(labelWidth / 3);
		GUISource.setTextColor(scoreTeamA, getLabelColor(game.getTeamA()));
		scoreTeamB = getNewScoreLabel(content.getWidth() - labelWidth + (labelWidth / 5 * 2));
		GUISource.setTextColor(scoreTeamB, getLabelColor(game.getTeamB()));
	}
	
	private Color getLabelColor(Team team) {
		return (team == game.getCurrentPlayer().getTeam() ? Color.BLUE : Color.RED);
	}
	
	private InterfaceLabel getNewScoreLabel(int x) {
		InterfaceLabel scoreLabel = new InterfaceLabel("0", labelFont);
		scoreLabel.setXY(x, labelY);
		scoreLabel.setSize(labelWidth, labelHeight);
		content.addWidget(scoreLabel);
		return scoreLabel;
	}
	
	private void initListener(final Team team) {
		TeamListener l = new TeamListener() {
			@Override
			public void teamValueChanged(TeamValueChangedEvent event) {
				if(event.getType() == TeamValueType.Score) 
					updateScoreLabel(team == game.getTeamA() ? scoreTeamA : scoreTeamB, team.getTeamScore());
			}
			
			@Override
			public void playerRemoved(Player player) {}
			@Override
			public void playerAdded(Player player) {}
			@Override
			public void droneDestroyed(DroneKillEvent event) {}
		};
		
		hud.addListener(team, l);
	}
	
	private void updateScoreLabel(InterfaceLabel label, int score) {
		label.setText(score + "");
		
		if(label == scoreTeamB) {
			int x = content.getWidth() - labelFont.getWidth(label.getText()) - scoreTeamA.getX();
			label.setX(x);
		}
		
		layout();
	}
}